package org.tech4j.springboot.starter.logging.common.context;

import com.google.common.collect.Maps;

import java.util.Map;

/**
 * @program: tech4j
 * @description:
 * @author: YuKai Fan
 * @create: 2025/3/6 15:25
 **/
public class LogAttributes {
    private final String LOG_USER_ID_ATTR = "user_id";
    private final String LOG_OPERATE_ATTR = "operator";
    private final String LOG_TENANT_ID_ATTR = "tenant_id";
    private final String LOG_TRACE_ID_ATTR = "trace_id";
    protected volatile Map<String, String> attachments = Maps.newHashMap();

    public LogAttributes() {
    }

    public LogAttributes setUserIdAttr(String userId) {
        return setAttachment(LOG_USER_ID_ATTR, userId);
    }

    public LogAttributes setOperatorAttr(String operator) {
        return setAttachment(LOG_OPERATE_ATTR, operator);
    }

    public LogAttributes setTenantIdAttr(String tenantId) {
        return setAttachment(LOG_TENANT_ID_ATTR, tenantId);
    }

    public LogAttributes setTraceIdAttr(String traceId) {
        return setAttachment(LOG_TRACE_ID_ATTR, traceId);
    }

    public String getTraceIdAttr() {
        return getAttachment(LOG_TRACE_ID_ATTR);
    }

    public String getUserIdAttr() {
        return getAttachment(LOG_USER_ID_ATTR);
    }

    public String getOperatorAttr() {
        return getAttachment(LOG_OPERATE_ATTR);
    }

    public String getTenantIdAttr() {
        return getAttachment(LOG_TENANT_ID_ATTR);
    }

    public LogAttributes setAttachment(String key, String value) {
        if (value == null) {
            attachments.remove(key);
        } else {
            attachments.put(key, value);
        }
        return this;
    }

    public LogAttributes removeAttachment(String key) {
        attachments.remove(key);
        return this;
    }

    public String getAttachment(String key) {
        return attachments.get(key);
    }

    public String getAttachment(String key, String defaultValue) {
        return attachments.getOrDefault(key, defaultValue);
    }

    public Map<String, String> getAttachments() {
        return attachments;
    }


    public LogAttributes setAttachments(Map<String, String> attachment) {
        this.attachments.clear();
        if (attachment != null && !attachment.isEmpty()) {
            this.attachments.putAll(attachment);
        }
        return this;
    }
}
